<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CommentsController extends Controller
{
	/**
	 * 评论列表
	 */
	public function getIndex(Request $request)
	{
		// 显示模板
		// return view('comments.index');

		// 读取数据 并且分页
        $comments = DB::table('goodscomment')
        ->leftJoin('goods','goodscomment.goodsid','=','goods.id')
        ->leftJoin('users','goodscomment.userid','=','users.id')
        ->leftJoin('recontents','recontents.comment_id','=','goodscomment.id')
        ->select('goodscomment.*','goods.proname','users.username','recontents.content','recontents.recont')
        ->where(function($query)use($request){
            $query->where('proname','like','%'.$request->input('keywords').'%');
        })
        ->paginate($request->input('num',10));


        // 解析模板
        return view('comments.index',['comments'=>$comments,'request'=>$request->all()]);
	}

	/**
	 * 查看评论详情
	 */
	public function getCheck($id)
	{

		// 查询数据
        $res = DB::table('goodscomment')
        ->leftJoin('goods','goodscomment.goodsid','=','goods.id')
        ->leftJoin('users','goodscomment.userid','=','users.id')
        ->leftJoin('recontents','recontents.comment_id','=','goodscomment.id')
        ->select('goodscomment.*','goods.proname','users.username','recontents.content','recontents.recont')
        ->where('goodscomment.id',$id)
        ->first();
        // 显示模板 分配变量
        return view('comments.check',['comments'=>$res]);
	}

	/**
	 * 回复评论
	 */
	public function postUpdate(Request $request)
	{
		// 接收数据
		$date = $request->only(['recont','retime']);
        $content = $request->input('cont');
        // 执行修改
        $res = DB::table('recontents')->where('content',$content)->update($date);
        if($res){
            // 成功 重定向 页面跳转列表页
            return redirect('admin/comments/index')->with('success','回复评论成功');
        }else{
            // 失败 回到添加页
            return back()->with('error','回复评论失败');
        }
	}
}
